<?php
if (!file_exists('../install.lock')) {
    header('Location: ../install.php');
    exit;
}

require_once 'config.php';
require_once 'alipay.php';

$settings = getSettings();
$error = '';
$success = '';

// 处理支付请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = intval($_POST['product_id'] ?? 0);
    $quantity = 1;
    // 生成/获取user_token
    if (empty($_COOKIE['user_token'])) {
        $user_token = bin2hex(random_bytes(16));
        setcookie('user_token', $user_token, time() + 3600*24*30, "/");
    } else {
        $user_token = $_COOKIE['user_token'];
    }
    $card_password = trim($_POST['card_password'] ?? '');
    if (strlen($card_password) < 4) {
        $error = '取卡密码不能少于4位';
    } else if ($product_id > 0 && $quantity > 0) {
        // 获取商品信息
        $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ? AND status = 1");
        $stmt->execute([$product_id]);
        $product = $stmt->fetch();
        if ($product) {
            // 购买限制校验
            $purchase_limit = isset($product['purchase_limit']) ? intval($product['purchase_limit']) : 0;
            if ($purchase_limit > 0) {
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE user_token = ? AND product_id = ? AND status = 'paid'");
                $stmt->execute([$user_token, $product_id]);
                $paid_count = $stmt->fetchColumn();
                if ($paid_count >= $purchase_limit) {
                    $error = '该商品每人限购' . $purchase_limit . '次，您已达上限';
                }
            }
            if (empty($error)) {
                $total_amount = $product['price'] * $quantity;
                $order_no = generateOrderNo();
                $card_password_hash = md5($card_password);
                // 创建订单，写入user_token和card_password
                $stmt = $pdo->prepare("INSERT INTO orders (order_no, product_id, quantity, total_amount, status, created_at, user_token, card_password) VALUES (?, ?, ?, ?, 'pending', NOW(), ?, ?)");
                $stmt->execute([$order_no, $product_id, $quantity, $total_amount, $user_token, $card_password_hash]);
                // 跳转到支付页面
                header("Location: payment.php?order_no=" . $order_no);
                exit;
            }
        } else {
            $error = '商品不存在或已下架';
        }
    } else if (!$error) {
        $error = '请选择商品和数量';
    }
}

// 获取商品列表
$stmt = $pdo->query("SELECT * FROM products WHERE status = 1 ORDER BY sort_order ASC, id ASC");
$products = $stmt->fetchAll();

$pay_configured = !empty($settings['alipay_app_id']) && !empty($settings['alipay_private_key']) && !empty($settings['alipay_public_key']);
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title><?php echo htmlspecialchars($settings['title'] ?? '卡密购买'); ?> - 在线购买</title>
    <link rel="shortcut icon" type="image/x-icon" href="../assets/favicon.ico">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <link rel="stylesheet" type="text/css" href="../assets/css/materialdesignicons.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/animate.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/style.min.css">
    <style>
        .product-card {
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        .price-tag {
            background: linear-gradient(45deg, #ff6b6b, #ee5a24);
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            font-weight: bold;
        }
        .hero-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 60px 0;
            margin-bottom: 40px;
        }
        html, body, .lyear-layout-web, .lyear-layout-container, .lyear-layout-content {
            width: 100% !important;
            min-width: 0 !important;
            margin: 0 !important;
            padding: 0 !important;
        }
    </style>
</head>

<body>
<!--页面loading-->
<div id="lyear-preloader" class="loading">
    <div class="ctn-preloader">
        <div class="round_spinner">
            <div class="spinner"></div>
            <img src="../assets/images/loading-logo.png" alt="">
        </div>
    </div>
</div>
<!--页面loading end-->

<div class="lyear-layout-web">
    <div class="lyear-layout-container">
        <!-- 导航栏 -->
        <nav class="navbar navbar-expand-lg navbar-light bg-white border-bottom w-100" style="margin:0;padding:0;">
            <div class="container-fluid px-4">
                <a class="navbar-brand" href="#">
                    <?php echo htmlspecialchars($settings['title'] ?? '卡密购买'); ?>
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav ms-auto">
                        <li class="nav-item">
                            <a class="nav-link" href="../index.php">返回首页</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="orders.php">我的订单</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
        
        <!--页面主要内容-->
        <main class="lyear-layout-content">
            <!-- 英雄区域 -->
            <div class="hero-section">
                <div class="container text-center">
                    <h1 class="display-4 mb-3">在线购买卡密</h1>
                    <p class="lead mb-0">安全便捷的支付体验，即时发货</p>
                </div>
            </div>
            
            <div class="container-fluid p-t-15">
                <?php if ($error): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <strong>错误！</strong> <?php echo $error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong>成功！</strong> <?php echo $success; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <!-- 商品列表 -->
                <div class="row justify-content-center">
                    <?php if (empty($products)): ?>
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body text-center">
                                    <i class="mdi mdi-package-variant mdi-48px text-muted"></i>
                                    <h4 class="mt-3">暂无商品</h4>
                                    <p class="text-muted">请稍后再来查看</p>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <?php foreach ($products as $product): ?>
                            <div class="col-lg-4 col-md-6 mb-4">
                                <div class="card product-card h-100">
                                    <div class="card-body text-center">
                                        <div class="mb-3">
                                            <i class="mdi mdi-credit-card mdi-48px text-primary"></i>
                                        </div>
                                        <h5 class="card-title"><?php echo htmlspecialchars($product['name']); ?></h5>
                                        <p class="card-text text-muted">
                                            <?php
                                            $type_map = [
                                                'minute' => '分钟',
                                                'hour' => '小时',
                                                'day' => '天',
                                                'week' => '周',
                                                'month' => '月',
                                                'season' => '季',
                                                'quarter' => '季',
                                                'year' => '年',
                                                'forever' => '永久',
                                                '分钟' => '分钟',
                                                '小时' => '小时',
                                                '天' => '天',
                                                '周' => '周',
                                                '月' => '月',
                                                '季' => '季',
                                                '年' => '年',
                                                '永久' => '永久'
                                            ];
                                            if ($product['duration_type'] === 'forever' || $product['duration_type'] === '永久') {
                                                echo '永久使用时长';
                                            } else {
                                                $type = $type_map[$product['duration_type']] ?? $product['duration_type'];
                                                echo $product['duration_value'] . $type . '使用时长';
                                            }
                                            ?>
                                        </p>
                                        <div class="mb-3">
                                            <span class="price-tag">￥<?php echo number_format($product['price'], 2); ?></span>
                                        </div>
                                        <form method="POST" class="d-inline product-buy-form" id="buy_form_<?php echo $product['id']; ?>">
                                            <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
                                            <input type="hidden" name="card_password" id="card_password_<?php echo $product['id']; ?>">
                                            <button type="button" class="btn btn-primary btn-lg" onclick="showPasswordModal(<?php echo $product['id']; ?>)" <?php if(!$pay_configured) echo 'disabled'; ?>>
                                                <i class="mdi mdi-cart-plus"></i> <?php echo $pay_configured ? '立即购买' : '暂未配置支付'; ?>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                
                <!-- 购买说明 -->
                <div class="row mt-5">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h4><i class="mdi mdi-information-outline"></i> 购买说明</h4>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-3 text-center mb-3">
                                        <i class="mdi mdi-credit-card-plus mdi-36px text-primary"></i>
                                        <h6 class="mt-2">选择商品</h6>
                                        <p class="text-muted small">选择您需要的卡密类型和数量</p>
                                    </div>
                                    <div class="col-md-3 text-center mb-3">
                                        <i class="mdi mdi-qrcode mdi-36px text-success"></i>
                                        <h6 class="mt-2">扫码支付</h6>
                                        <p class="text-muted small">使用支付宝扫码完成支付</p>
                                    </div>
                                    <div class="col-md-3 text-center mb-3">
                                        <i class="mdi mdi-email-fast mdi-36px text-warning"></i>
                                        <h6 class="mt-2">自动发货</h6>
                                        <p class="text-muted small">支付成功后自动发送卡密</p>
                                    </div>
                                    <div class="col-md-3 text-center mb-3">
                                        <i class="mdi mdi-check-circle mdi-36px text-info"></i>
                                        <h6 class="mt-2">使用卡密</h6>
                                        <p class="text-muted small">在系统中使用卡密激活服务</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script src="../assets/js/jquery.min.js"></script>
<script src="../assets/js/popper.min.js"></script>
<script src="../assets/js/bootstrap.bundle.min.js"></script>
<script src="../assets/js/perfect-scrollbar.min.js"></script>
<script src="../assets/js/main.min.js"></script>
<script>
var currentProductId = null;
function showPasswordModal(productId) {
    currentProductId = productId;
    document.getElementById('modal_card_password').value = '';
    var modal = new bootstrap.Modal(document.getElementById('passwordModal'));
    modal.show();
    window.passwordModalInstance = modal;
}
function submitBuyForm() {
    var pwd = document.getElementById('modal_card_password').value;
    if (!pwd || pwd.length < 4) {
        alert('取卡密码不能少于4位');
        return;
    }
    document.getElementById('card_password_' + currentProductId).value = pwd;
    document.getElementById('buy_form_' + currentProductId).submit();
    if (window.passwordModalInstance) {
        window.passwordModalInstance.hide();
    }
}
</script>
<!-- 全局密码输入弹窗Modal（只出现一次，放在循环后） -->
<div class="modal fade" id="passwordModal" tabindex="-1" aria-labelledby="passwordModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="passwordModalLabel">请设置取卡密码</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <input type="password" class="form-control" id="modal_card_password" placeholder="设置4-32位取卡密码" minlength="4" maxlength="32" required autofocus>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" onclick="submitBuyForm()">确认购买</button>
      </div>
    </div>
  </div>
</div>
</body>
</html> 